package friend

import (
  "log"
  "net/http"
  "github.com/emicklei/go-restful"
)

type Friend struct {
  MySn, FriendSn string
}

type FriendList struct {
  friends map[string]string
}

// swagger:operation POST /add friend AddFriend
// ---
// summary: add function.
// description: append a object to storage.
// parameters:
// - name: add
//   in: object
//   description: name of object
//   type: string
//   required: true
func (f FriendList) AddFriend(request *restful.Request, response *restful.Response) {
  user := new(Friend)
  if err := request.ReadEntity(&user); err == nil {
    f.friends[user.MySn] = user.FriendSn
    f.friends[user.FriendSn] = user.MySn
    response.WriteEntity(user)
  } else {
    response.AddHeader("Content-Type", "text/plain")
    response.WriteErrorString(http.StatusInternalServerError, err.Error())
  }
}

// swagger:operation POST /delete friend DelFriend
// ---
// summary: delete function.
// description: If object is exist, delete it.
// parameters:
// - name: delete
//   in: object
//   description: identity of object
//   type: string
//   required: true
func (f FriendList) DelFriend(request *restful.Request, response *restful.Response) {
  user := new(Friend)
  if err := request.ReadEntity(&user); err == nil {
    if _, ok := f.friends[user.MySn]; ok {
      delete(f.friends, user.MySn);
      delete(f.friends, user.FriendSn);
    }
  }
}

// swagger:operation GET /list/{mySn} friend FindFriend
// ---
// summary: query function.
// description: If object is exist, delete it.
// parameters:
// - name: query
//   in: object
//   description: identity of object
//   type: string
//   required: true
func (f FriendList) FindFriend(request *restful.Request, response *restful.Response) {
  mySn := request.PathParameter("mySn")
  log.Printf("FindFriend with sn:%s", mySn)
  if friendSn, ok := f.friends[mySn]; ok {
    response.WriteEntity(friendSn)
  } else {
    response.AddHeader("Content-Type", "text/plain")
    response.WriteErrorString(http.StatusNotFound, "user not found.")
  }
}
